package com.zzyl.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class JwtTokenUtil {
    private static final String SECRET_KEY = "abcdefghijklmnopqrstuvwxyz"; // 替换为你的密钥

    public static String getTokenFromRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                return authHeader.substring(7); // 去掉 "Bearer " 前缀
            }
        }
        return null;
    }

    public static io.jsonwebtoken.Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    public static Claims getClaimsFromRequest() {
        String token = getTokenFromRequest();
        if (token != null) {
            return parseToken(token);
        }
        return null;
    }
}